package com.tac.service.impl;

import com.tac.common.Exception.CostomException;
import com.tac.common.result.Result;
import com.tac.common.thread.Thread;
import com.tac.dao.CollectionDao;
import com.tac.dao.ProductDao;
import com.tac.pojo.Collection;
import com.tac.pojo.Product;
import com.tac.service.CollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CollectionServiceImpl implements CollectionService {
    @Autowired
    private CollectionDao collectionDao;
    @Autowired
    private ProductDao productDao;
    /**
     * 添加收藏
     * @param pid
     * @return
     */
    public Result save(Integer pid){
        //先判断商品存在不
        Product product = productDao.selectById(pid);
        if(product==null){
            throw new CostomException("商品不存在");
        }
        //再判断是不是已经收藏了
        Collection collection = collectionDao.selectByPidAndUid(pid, Thread.getId());
        if(collection!=null){
            throw new CostomException("已收藏");
        }
        Integer save = collectionDao.save(pid, Thread.getId());
        if(save>0){
            return Result.success(null,"success");
        }
        throw new CostomException("收藏失败");
    }
    /**
     * 删除收藏
     * @param
     * @return
     */
    public Result remove(Integer pid){
        Integer remove = collectionDao.remove(pid, Thread.getId());
        if(remove>0){
            return Result.success(null,"success");
        }
        throw new CostomException("删除失败");
    }

    /**
     * 查看收藏所有商品 按时间倒序排列
     * @param
     * @return
     */
    public Result<List<Product>> selectByUid(){
        List<Integer> integers = collectionDao.selectByUid(Thread.getId());
        ArrayList<Product> products = new ArrayList<>();
        for(Integer integer:integers){
            Product product = productDao.selectById(integer);
            if(product!=null) {
                products.add(product);
            }
        }
        return Result.success(products,"success");
    }
    /**
     * 管理员查看收藏所有商品 按时间倒序排列
     * @param
     * @return
     */
    public Result<List<Collection>> selectAll(){
        List<Collection> collections = collectionDao.selectAll();
        for(Collection collection:collections){
            Product product = productDao.selectById(collection.getProductId());
            collection.setProduct(product);
        }
        return Result.success(collections,"success");
    }
    /**
     * 管理员删除收藏
     * @param pid
     * @param uid
     * @return
     */
    public Result delete(Integer pid,Integer uid){
        Integer remove = collectionDao.remove(pid, uid);
        if(remove>0){
            return Result.success(null,"success");
        }
        throw new CostomException("删除失败");
    }
}
